//
//  InstitutionalAppointmentVC.swift
//  Venus
//
//  Created by point on 2018/10/9.
//  Copyright © 2018年 zhaowang. All rights reserved.
//

import UIKit
import MJRefresh
import SwiftyJSON

private let cellID = "cellID"

class InstitutionalAppointmentVC: BaseViewController {
    
    lazy var topView:InstitutionalAppointmentTopView = InstitutionalAppointmentTopView(frame: CGRect.zero)
    
    fileprivate lazy var appointmentRemarkView:AppointmentRemarkView = AppointmentRemarkView(frame: CGRect.zero)
    
    lazy var tableView : UITableView = {
        let tableView = UITableView(frame: CGRect.zero, style: .grouped)
        tableView.showsVerticalScrollIndicator = false
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.register(InstitutionalAppointmentTableViewCell.self, forCellReuseIdentifier: cellID)
        return tableView
    }()
    
    fileprivate var type:Int = 0 //0最新 1历史
    
    fileprivate var vmModel:InstitutionalAppointmentVM = InstitutionalAppointmentVM()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
}

// MARK: - 遵守上拉 下拉协议
extension InstitutionalAppointmentVC: RefreshControl {
    
    func refreshingAction(refreshControl: MJRefreshNormalHeader) {
        if type == 0 {
            vmModel.loadData()
        }else {
            vmModel.loadDataHistory()
        }
    }
    
    func refreshingActionFooter(refreshControl: MJRefreshAutoNormalFooter) {
        if type == 0 {
            vmModel.loadDataMore()
        }else {
            vmModel.loadDataMoreHistory()
        }
    }
    
}

// MARK: - 交互
extension InstitutionalAppointmentVC: InstitutionalAppointmentTopViewDelegate , InstitutionalAppointmentTableViewCellDelegate {
    func clickTopViewItem(index: Int) {
        type = index
        self.tableView.mj_header.beginRefreshing()
    }
    
    func clickInstitutionalAppointmentTableViewCellBtn(cell: InstitutionalAppointmentTableViewCell, index: Int) {
        if index == 0 {
            appointmentRemarkView.isHidden = false
            appointmentRemarkView.mytextView.becomeFirstResponder()
        }else {
            
            var uid:String = ""
            if type == 0 {
                uid = vmModel.newInstitutionAppointModel[cell.tag].id
            }else {
                uid = vmModel.historyInstitutionAppointModel[cell.tag].id
            }
            self.hudLoad()
            let url = kHost + kInstitutionCallUser + "".apiFOperator(time: "1", sign: "1") + "&phoneKey=" + "sss" + "&userId=" + uid + "&id=" + String(  UserInfo.shareInstance.userModel().institutionId)
            
            TempNetTool.post(url, parameters: nil, progress: nil, success: { [weak self](result) in
                self?.hudHide()
                let json = JSON(result as Any)
                let tel = json["data"].stringValue
                UIApplication.shared.open(NSURL.init(string: "tel://\(String(describing: tel))")! as URL, options: [:], completionHandler: nil)
            }) { [weak self] (error) in
                self?.hudError()
            }
        }
        
    }
    
    @objc func exitMask() {
        appointmentRemarkView.isHidden = true
        appointmentRemarkView.mytextView.resignFirstResponder()
    }
}

// MARK:- 代理
extension InstitutionalAppointmentVC:UITableViewDelegate , UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if type == 0 {
            return vmModel.newInstitutionAppointModel.count
            
        }else {
            return vmModel.historyInstitutionAppointModel.count
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView .dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! InstitutionalAppointmentTableViewCell
        cell.delegate = self
        if type == 0 {
            cell.configModel(model: vmModel.newInstitutionAppointModel[indexPath.item], index: indexPath)
        }else {
            cell.configModel(model: vmModel.historyInstitutionAppointModel[indexPath.item], index: indexPath)
            
        }
        cell.tag = indexPath.item
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.001
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70
    }
}

// MARK: - 设置UI
extension InstitutionalAppointmentVC {
    func setupUI() {
        view.backgroundColor = nC1
        vmModel.vc = self
        title = "查看预约详情"
        view.addSubview(topView)
        view.addSubview(tableView)
        view.addSubview(appointmentRemarkView)
        topView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(LayoutCommon.navHeight)
            make.height.equalTo(50)
        }
        topView.dalegate = self
        
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(view).offset(LayoutCommon.navHeight + 55)
            make.left.right.equalToSuperview()
            if #available(iOS 11.0, *) {
                make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
            } else {
                make.bottom.equalTo(view.snp.bottom)
            }
        }
        tableView.backgroundColor = UIColor.white
        
        appointmentRemarkView.snp.makeConstraints { (make) in
            make.top.equalTo(view).offset(LayoutCommon.navHeight)
            make.left.right.equalToSuperview()
            if #available(iOS 11.0, *) {
                make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
            } else {
                make.bottom.equalTo(view.snp.bottom)
            }
        }
        appointmentRemarkView.isHidden = true
        appointmentRemarkView.mytextView.addDoneOnKeyboardWithTarget(self, action: #selector(exitMask))
        
        setupRefreshControl(scrollView: self.tableView, target: self)
        setupRefreshFootControl(scrollView:  self.tableView, target: self)
        self.tableView.mj_header.beginRefreshing()
        
    }
}
